<template>
  <view class="container">
    <!-- 商品图片轮播 -->
    <view class="product-images">
      <swiper class="image-swiper" indicator-dots circular>
        <swiper-item v-for="(image, index) in productImages" :key="index">
          <image :src="image" mode="aspectFill" class="product-image" @click="previewImage(index)" />
        </swiper-item>
      </swiper>
    </view>

    <!-- 商品基本信息 -->
    <view class="product-info">
      <view class="product-price">
        <text class="current-price">¥{{ formatPrice(selectedSku ? selectedSku.price : product.price) }}</text>
        <text v-if="selectedSku && selectedSku.originalPrice && selectedSku.originalPrice > selectedSku.price" class="original-price">
          ¥{{ formatPrice(selectedSku.originalPrice) }}
        </text>
      </view>
      <view class="product-name">{{ product.name }}</view>
      <view class="product-desc">{{ product.description }}</view>
      
      <!-- 商品标签 -->
      <view class="product-tags" v-if="product.tags && product.tags.length">
        <text v-for="tag in product.tags" :key="tag.id" class="tag">{{ tag.name }}</text>
      </view>
      
      <!-- 销量和库存 -->
      <view class="product-stats">
        <text class="stat-item">销量 {{ product.sales || 0 }}</text>
        <text class="stat-item">库存 {{ selectedSku ? selectedSku.stock : product.stock }}</text>
      </view>
    </view>

    <!-- SKU选择 -->
    <view class="sku-section" v-if="productSkus.length > 0">
      <view class="section-title">规格选择</view>
      <view class="sku-list">
        <view 
          class="sku-item"
          :class="{ active: selectedSku && selectedSku.id === sku.id }"
          v-for="sku in productSkus"
          :key="sku.id"
          @click="selectSku(sku)"
        >
          <text class="sku-name">{{ sku.specifications || '默认规格' }}</text>
          <text class="sku-price">¥{{ formatPrice(sku.price) }}</text>
        </view>
      </view>
    </view>

    <!-- 商品详情 -->
    <view class="detail-section">
      <view class="section-title">商品详情</view>
      <view class="detail-content">
        <rich-text :nodes="product.detailContent || '暂无详情'"></rich-text>
      </view>
    </view>

    <!-- 商品评价 -->
    <view class="review-section">
      <view class="section-header">
        <text class="section-title">商品评价</text>
        <text class="review-count">({{ reviewCount }})</text>
        <text class="more-link" @click="goToReviews">查看更多</text>
      </view>
      <view class="review-list">
        <view 
          class="review-item"
          v-for="review in reviews"
          :key="review.id"
        >
          <view class="review-header">
            <image :src="review.userAvatar || '/static/images/default-avatar.png'" class="user-avatar" />
            <view class="review-info">
              <text class="username">{{ review.username }}</text>
              <view class="rating">
                <text v-for="i in 5" :key="i" class="star" :class="{ active: i <= review.rating }">★</text>
              </view>
            </view>
            <text class="review-time">{{ formatDate(review.createdAt) }}</text>
          </view>
          <text class="review-content">{{ review.comment }}</text>
        </view>
      </view>
    </view>

    <!-- 底部操作栏 -->
    <view class="bottom-bar">
      <view class="action-buttons">
        <view class="action-btn" @click="toggleFavorite">
          <text class="action-icon">{{ isFavorite ? '❤️' : '🤍' }}</text>
          <text class="action-text">收藏</text>
        </view>
        <view class="action-btn" @click="goToCart">
          <text class="action-icon">🛒</text>
          <text class="action-text">购物车</text>
        </view>
      </view>
      
      <view class="buy-buttons">
        <button class="add-cart-btn" @click="addToCart">加入购物车</button>
        <button class="buy-now-btn" @click="buyNow">立即购买</button>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { onLoad } from '@dcloudio/uni-app';
import { productApi, cartApi, favoriteApi, reviewApi } from '@/api/index.js';
import common from '@/utils/common.js';
import storage from '@/utils/storage.js';

// 响应式数据
const productId = ref(null);
const product = ref({});
const productSkus = ref([]);
const selectedSku = ref(null);
const productImages = ref([]);
const reviews = ref([]);
const reviewCount = ref(0);
const isFavorite = ref(false);
const loading = ref(false);

// 格式化价格
const formatPrice = (price) => {
  return common.formatPrice(price);
};

// 格式化日期
const formatDate = (date) => {
  return common.formatDate(date, 'MM-DD');
};

// 加载商品详情
const loadProductDetail = async () => {
  try {
    common.showLoading('加载中...');
    const res = await productApi.getProductById(productId.value);
    product.value = res.data;
    
    // 处理商品图片
    if (product.value.imageUrl) {
      productImages.value = [product.value.imageUrl];
    }
    if (product.value.images) {
      productImages.value = [...productImages.value, ...product.value.images];
    }
  } catch (error) {
    console.error('加载商品详情失败:', error);
    common.showError('加载失败');
  } finally {
    common.hideLoading();
  }
};

// 加载商品SKU
const loadProductSkus = async () => {
  try {
    const res = await productApi.getProductSkus(productId.value);
    productSkus.value = res.data || [];
    
    // 默认选择第一个SKU
    if (productSkus.value.length > 0) {
      selectedSku.value = productSkus.value[0];
    }
  } catch (error) {
    console.error('加载商品SKU失败:', error);
  }
};

// 加载评价
const loadReviews = async () => {
  try {
    const res = await reviewApi.getProductReviews(productId.value, { limit: 3 });
    reviews.value = res.data || [];
    reviewCount.value = reviews.value.length;
  } catch (error) {
    console.error('加载评价失败:', error);
  }
};

// 检查收藏状态
const checkFavorite = async () => {
  const token = storage.getToken();
  if (!token) return;

  try {
    const res = await favoriteApi.checkFavorite(productId.value);
    isFavorite.value = res.data || false;
  } catch (error) {
    console.error('检查收藏状态失败:', error);
  }
};

// 选择SKU
const selectSku = (sku) => {
  selectedSku.value = sku;
};

// 预览图片
const previewImage = (index) => {
  uni.previewImage({
    current: index,
    urls: productImages.value
  });
};

// 切换收藏
const toggleFavorite = async () => {
  const token = storage.getToken();
  if (!token) {
    uni.navigateTo({
      url: '/pages/login/login'
    });
    return;
  }

  try {
    if (isFavorite.value) {
      await favoriteApi.removeFavorite(productId.value);
      common.showSuccess('取消收藏成功');
    } else {
      await favoriteApi.addFavorite(productId.value);
      common.showSuccess('收藏成功');
    }
    isFavorite.value = !isFavorite.value;
  } catch (error) {
    console.error('操作收藏失败:', error);
    common.showError('操作失败');
  }
};

// 添加到购物车
const addToCart = async () => {
  const token = storage.getToken();
  if (!token) {
    uni.navigateTo({
      url: '/pages/login/login'
    });
    return;
  }

  if (!selectedSku.value) {
    common.showError('请选择商品规格');
    return;
  }

  try {
    common.showLoading('添加中...');
    await cartApi.addToCart({
      productId: productId.value,
      skuId: selectedSku.value.id,
      quantity: 1
    });
    common.showSuccess('添加成功');
  } catch (error) {
    console.error('添加购物车失败:', error);
    common.showError('添加失败');
  } finally {
    common.hideLoading();
  }
};

// 立即购买
const buyNow = async () => {
  const token = storage.getToken();
  if (!token) {
    uni.navigateTo({
      url: '/pages/login/login'
    });
    return;
  }

  if (!selectedSku.value) {
    common.showError('请选择商品规格');
    return;
  }

  // 跳转到确认订单页面
  uni.navigateTo({
    url: `/pages/order/confirm?product_id=${productId.value}&sku_id=${selectedSku.value.id}&quantity=1`
  });
};

// 跳转到购物车
const goToCart = () => {
  uni.switchTab({
    url: '/pages/cart/cart'
  });
};

// 跳转到评价页面
const goToReviews = () => {
  uni.navigateTo({
    url: `/pages/review/list?productId=${productId.value}&productName=${encodeURIComponent(product.value.name)}`
  });
};

// 生命周期钩子
onLoad((options) => {
  if (options.id) {
    productId.value = options.id;
    loadProductDetail();
    loadProductSkus();
    loadReviews();
    checkFavorite();
  } else {
    console.error('商品ID未提供');
    common.showError('商品ID未提供');
    uni.navigateBack(); // 返回上一页
  }
});
</script>

<style scoped>
.container {
  min-height: 100vh;
  background: #f5f5f5;
  padding-bottom: 120rpx;
}

.product-images {
  background: #fff;
}

.image-swiper {
  height: 500rpx;
}

.product-image {
  width: 100%;
  height: 100%;
}

.product-info {
  background: #fff;
  padding: 30rpx;
  margin-bottom: 20rpx;
}

.product-price {
  margin-bottom: 20rpx;
}

.current-price {
  font-size: 48rpx;
  font-weight: bold;
  color: #ff4757;
  margin-right: 20rpx;
}

.original-price {
  font-size: 28rpx;
  color: #999;
  text-decoration: line-through;
}

.product-name {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
  margin-bottom: 15rpx;
}

.product-desc {
  font-size: 26rpx;
  color: #666;
  margin-bottom: 20rpx;
  line-height: 1.5;
}

.product-tags {
  margin-bottom: 20rpx;
}

.tag {
  display: inline-block;
  background: #f0f0f0;
  color: #666;
  font-size: 22rpx;
  padding: 8rpx 16rpx;
  border-radius: 20rpx;
  margin-right: 15rpx;
  margin-bottom: 10rpx;
}

.product-stats {
  display: flex;
  gap: 30rpx;
}

.stat-item {
  font-size: 24rpx;
  color: #999;
}

.sku-section {
  background: #fff;
  padding: 30rpx;
  margin-bottom: 20rpx;
}

.section-title {
  font-size: 28rpx;
  font-weight: bold;
  color: #333;
  margin-bottom: 20rpx;
}

.sku-list {
  display: flex;
  flex-wrap: wrap;
  gap: 20rpx;
}

.sku-item {
  border: 2rpx solid #ddd;
  border-radius: 8rpx;
  padding: 15rpx 20rpx;
  min-width: 120rpx;
  text-align: center;
}

.sku-item.active {
  border-color: #ff4757;
  background: #fff5f5;
}

.sku-name {
  font-size: 24rpx;
  color: #333;
  display: block;
  margin-bottom: 5rpx;
}

.sku-price {
  font-size: 22rpx;
  color: #ff4757;
  font-weight: bold;
}

.detail-section {
  background: #fff;
  padding: 30rpx;
  margin-bottom: 20rpx;
}

.detail-content {
  font-size: 26rpx;
  color: #666;
  line-height: 1.6;
}

.review-section {
  background: #fff;
  padding: 30rpx;
}

.section-header {
  display: flex;
  align-items: center;
  margin-bottom: 20rpx;
}

.review-count {
  font-size: 24rpx;
  color: #999;
  margin-left: 10rpx;
}

.more-link {
  font-size: 24rpx;
  color: #666;
  margin-left: auto;
}

.review-list {
  max-height: 400rpx;
  overflow-y: auto;
}

.review-item {
  padding: 20rpx 0;
  border-bottom: 1rpx solid #f0f0f0;
}

.review-item:last-child {
  border-bottom: none;
}

.review-header {
  display: flex;
  align-items: center;
  margin-bottom: 15rpx;
}

.user-avatar {
  width: 60rpx;
  height: 60rpx;
  border-radius: 50%;
  margin-right: 15rpx;
}

.review-info {
  flex: 1;
}

.username {
  font-size: 26rpx;
  color: #333;
  margin-bottom: 5rpx;
  display: block;
}

.rating {
  display: flex;
  gap: 5rpx;
}

.star {
  font-size: 20rpx;
  color: #ddd;
}

.star.active {
  color: #ffd700;
}

.review-time {
  font-size: 22rpx;
  color: #999;
}

.review-content {
  font-size: 26rpx;
  color: #666;
  line-height: 1.5;
}

.bottom-bar {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  background: #fff;
  padding: 20rpx;
  display: flex;
  align-items: center;
  justify-content: space-between;
  border-top: 1rpx solid #eee;
}

.action-buttons {
  display: flex;
  gap: 30rpx;
}

.action-btn {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.action-icon {
  font-size: 32rpx;
  margin-bottom: 5rpx;
}

.action-text {
  font-size: 20rpx;
  color: #666;
}

.buy-buttons {
  display: flex;
  gap: 20rpx;
}

.add-cart-btn,
.buy-now-btn {
  border: none;
  border-radius: 25rpx;
  padding: 20rpx 30rpx;
  font-size: 26rpx;
}

.add-cart-btn {
  background: #ff9500;
  color: #fff;
}

.buy-now-btn {
  background: #ff4757;
  color: #fff;
}
</style> 